package com.boyinet.activation.controller;

import cn.hutool.core.date.DateUtil;
import com.boyinet.activation.entity.User;
import com.boyinet.activation.service.UserService;
import com.boyinet.activation.util.R;
import com.boyinet.activation.util.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lengchunyun
 */
@RestController
@Slf4j
@RequestMapping("auth")
public class AuthController {

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private UserService userService;

    @RequestMapping("refresh")
    public R refresh(HttpServletRequest request) {
        String refreshToken = request.getHeader("refresh_token");
        if (refreshToken != null) {
            log.info("[token refresh] at {}", DateUtil.now());
            String name = SecurityContextHolder.getContext().getAuthentication().getName();
            User user = userService.getUserByName(name);
            String token = tokenManager.createToken(name);
            user.setToken(token);
            user.setPassword(null);
            return R.ok().put("data", user);
        }
        return R.error();
    }
}
